While Loop in C
while loop is like a "do this while that's true" loop. It repeats a task over and over as long as a condition remains true. It's great when you're not sure how many times you need to do something. If you already know the exact number of times, use a for loop.
Syntax of While Loop:
// Code to be executed as long as the condition is true
}
Structure of a While Loop:
A while loop operates in a structured way, and you can break it down into several key parts:
1. Initialization: At the beginning, you set up the loop by initializing a variable with an initial value. This isn't directly part of the while loop syntax but is essential when you plan to use a variable in the condition that controls the loop.2. Conditional Statement: This step is critical because it determines whether the code within the while loop will run. The code inside the loop will execute only if the test condition specified in the conditional statement is true.
3. Body: The body is the actual sequence of statements that will run as long as the condition remains true. It's typically enclosed within curly braces { }.
4. Updation: In each iteration, you update the value of the loop variable using an expression. Like initialization, it's not part of the core syntax, but you need to include it explicitly within the loop's body.
How does a for Loop works?
Step 1: Condition Check, it checks a condition first. If the condition is initially false, the loop is skipped entirely.
Step 2: Code Execution, if the condition is true, it executes the code inside the loop.
Step 3: Condition Recheck, after executing the code, it checks the condition again.
Step 4: Repeat or Exit, if the condition is still true, it repeats the code execution. This continues until the condition becomes false.
Step 5: Loop Termination, once the condition becomes false, the loop ends, and the program proceeds with the code after the loop.
Example of While Loop:
Here's a basic example of a example loop in C that prints numbers from 1 to 5:
int main() {
int i = 1; // Initialization
while (i <= 5) { // Condition check
printf("Number: %d\n", i); // Code block
i++; // Updation
}
return 0;
}
In this example,
1. We start by initializing a variable i to 1.
2. The while loop is used to check the condition i <= 5.
3. If the condition is true, the code block inside the loop is executed, which prints the current value of i.
4. After the code block, the i variable is updated using i++ to increment its value.
5. The loop continues to repeat until the condition i <= 5 becomes false. In this case, it stops when i reaches 6.
6. Finally, the program returns 0 to indicate successful execution.